//<!-- 月票凭证 -->
import api from '../../../fetch/api'
import { deepCopyObj } from '../../../assets/js/help.js'
export default {
  data () {
    return {
      parkNameListRow: {
        searchParams:{},
        pageNumber:1,
        total: 0,
        theadsInfo: [
          { index: 0, isShow: false, prop: 'reno', text: '序号', width: 68 },
          { index: 1, isShow: false, prop: 'm', text: '停车场', minWidth: 110 }
        ],
        tbodysInfo: []
      },
      parkNameRow:{},
      bigImgPath: '',
      agreenment:{
        title:'',
        content:''
      },
      certifi_rule_modal_title:'',
      certifiModel:{
        id:null,
        telephone:null,
        remark1:null,
        remark2:null,
        remark3:null,
        expriedTime:null,
        certifiUrl:null,
        status:1,
        ticketName:null,
        reason:null
      },
      certifiRules:{
        expriedTime:[
          { required: true, message: '请选择到期时间'}
        ],
        remark1: [
          { min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'change' }
        ],
        remark2: [
          { min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'change' }
        ],
        remark3: [
          { min: 0, max: 100, message: '长度在 0 到 100 个字符', trigger: 'change' }
        ],
        reason: [
          { min: 0, max: 200, message: '长度在 0 到 200 个字符', trigger: 'change' }
        ]
      },
      delayModel:{
        months:1
      },
      ids:null,
      delayRules:{
        months:[
          { required: true, message: '请输入到期月份'}
        ]
      }
    }
  },
  created () {
    //this.toBase(this);
  },
  methods: {
    //图片转bas64
    showBigImgModal(name, path) {
        this.bigImgPath = path;
        this.toOpenImgModal(name, path);
    },
    toBase(vm) {
      console.log("执行了  this.toBase(this)")
      $(document).on('change', "#inCertifiSampleUrl", function () {
        console.log("执行了  this.toBase(this)》》》》.change")
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          // icon: 0:普通提示 1：正确的提示 2： 错误提示
          // time: 不填默认1000ms
          vm.showToast('请确保文件为图像类型', 2, 2000)
          return false;
        }
        vm.certifiRuleModel.inCertifiSampleName = file.name;
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          console.log(e);
          var res = e.target.result.replace("data:image/png;base64,", "");
          res = res.replace("data:image/jpg;base64,", "");
          res = res.replace("data:image/jpeg;base64,", "");
          vm.certifiRuleModel.inCertifiSample = res;
          vm.certifiRuleModel.inCertifiSampleUrl = "res";
          //console.log('vm.traderModalData.pic_base64', vm.certifiRuleModel.inCertifiSample)
        };
      });

      $(document).on('change', "#outCertifiSampleUrl", function () {
        console.log("执行了  this.toBase(this)》》》》.change")
        var file = this.files[0];
        var reader = new FileReader();
        if (!/image\/\w+/.test(file.type)) {
          // icon: 0:普通提示 1：正确的提示 2： 错误提示
          // time: 不填默认1000ms
          vm.showToast('请确保文件为图像类型', 2, 2000)
          return false;
        }
        vm.certifiRuleModel.outCertifiSampleName = file.name;
        reader.readAsDataURL(file);
        reader.onload = function (e) {
          console.log(e);
          var res = e.target.result.replace("data:image/png;base64,", "");
          res = res.replace("data:image/jpg;base64,", "");
          res = res.replace("data:image/jpeg;base64,", "");
          vm.certifiRuleModel.outCertifiSample = res;
          vm.certifiRuleModel.outCertifiSampleUrl = "res";
          //console.log('vm.traderModalData.pic_base64', vm.certifiRuleModel.inCertifiSample)
        };
      });
    },
    getDefaultParams(){//获取不能缺少的默认的参数
        let self = this;
        let searchParams = self.searchParams,
            searchList = self.searchList,
            result = {};
            //console.log(searchList);
            var submitTimeFromTo,query_status;
            for (var key in searchList) {
                if (searchList.hasOwnProperty(key)) {
                    var item = searchList[key];
                    if(item.name=='submitTimeFromTo'){
                        submitTimeFromTo = item;
                    }
                    if(item.name=='query_status'){
                        query_status = item;
                    }
                }
            }
              console.log(submitTimeFromTo.value);
            if(submitTimeFromTo && submitTimeFromTo!=null && submitTimeFromTo.value!=undefined && submitTimeFromTo.value[0]!=undefined && submitTimeFromTo.value[0]!=null){
                result.submitTimeFrom = moment(submitTimeFromTo.value[0]).format('YYYY-MM-DD HH:mm:ss');
                result.submitTimeTo = moment(submitTimeFromTo.value[1]).format('YYYY-MM-DD HH:mm:ss');
            }
            if(query_status && query_status!=null && query_status.value!=''){
                result.query_status = query_status.value;
            }
        return result;
    },
    getList () {
      let params = $.extend({}, this.searchParams, this.otherParams,this.getDefaultParams());
      this.getCertifiList(params);
    },
    getCertifiList (aparams) {//查询列表
      let self = this,
          params = {
            page: this.pageNumber,
            rp: this.pageSize
          };
      params = $.extend({}, params, aparams);

      API.monthTicket.GetCertifiListData(params)
          .then(res => {
            let data = res.data,
                list = data.rows;
            self.tbodysInfo = list;
            self.total = data.total;
          }, err => {})
    },
    exportCertifi(){
      let self = this;
      let theadsArr = []
      for(let i = 0; i<self.theadsInfo.length; i++){
        if(self.theadsInfo[i].checked){
          theadsArr.push(self.theadsInfo[i].prop)
        }
      }
      let params = $.extend({}, this.searchParams, this.otherParams,this.getDefaultParams());
      params.meterList = theadsArr.join(',')
      this.showDialog("是否确认导出记录？",[],function(){
        self.toExportAsync('/month_ticket/certifi/export.do', params);
      },"温馨提示",function(){
        //取消时不操作
      });
    },
    resetModelData(){
      let self = this;
      self.certifiModel={
        id:null,
        telephone:null,
        remark1:null,
        remark2:null,
        remark3:null,
        expriedTime:null,
        certifiUrl:null,
        status:1,
        ticketName:null,
        reason:null
      }
    },
    delayCertifi(modalName){
      let self = this;
      let ids = [];
      //判断是否选择了多行
      let idsStr = self.selectionList;
      if(idsStr<=0){
        this.showToast("请至少选择一项",0);
        return false;
      }else{
        ids = idsStr.split(",");
      }
      self.ids = idsStr;
      self.toOpenModal(modalName,1);
    },
    checkCertifi(modalName,row){
      let self = this;
      self.resetModelData();
      self.certifiModel = deepCopyObj(row);
      self.certifiModel.status = 1+'';
      self.certifiModel.expriedTime = new Date(moment(row.submitTime).add(1,'years').format('YYYY-MM-DD 23:59:59'));
      //获取
      self.toOpenModal(modalName,1);
    },
    delCertifiRule(row){
      var self = this;
      var params = {
          id: row.id,
          parkId:row.parkId
      };
      self.showDialog("确认删除"+row.parkName+"的月票配置?",'',function(){
        API.monthTicket.DelCertifiRule(params).then(res => {
          //start
          var data = res;
          if(res.message){
            self.showToast(res.message, 1, 2000);
          }else{
            self.showToast('删除成功', 1);                          
            self.getList();
          }
          //end
        }, err => {});
      });
    },
    submitDelayForm(formName,modalName){
       var self = this;
        self.$refs[formName].validate((valid) => {
          if (valid) {
            var params = {};
            params.ids = self.ids;
            params.months = self.delayModel.months;
            API.monthTicket.DelayCertifi(params)
            .then(res => {
              if(res.message){
                self.showToast(res.message, 1, 2000);
              }else{
                self.showToast('操作成功', 1, 2000);
                self.resetForm(formName);
                self.closed(modalName);
                self.getList();
              }
            }, err => {
              self.showToast(err.message, 1, 2000);
            });
          }
        });
    },
    submitForm(formName,modalName){
      var self = this;
      self.$refs[formName].validate((valid) => {
        if (valid) {
          var params = {};
          params.id = self.certifiModel.id;
          params.remark1 = self.certifiModel.remark1;
          params.remark2 = self.certifiModel.remark2;
          params.remark3 = self.certifiModel.remark3;
          params.expriedTimeStr = self.certifiModel.expriedTime.Format('yyyy-MM-dd 23:59:59');
          params.status = self.certifiModel.status;
          params.reason = self.certifiModel.reason;

          API.monthTicket.CheckCertifi(params)
          .then(res => {
            if(res.message){
              self.showToast(res.message, 1, 2000);
            }else{
              self.showToast('操作成功', 1, 2000);
              self.resetForm(formName);
              self.closed(modalName);
              self.getList();
            }
          }, err => {
            self.showToast(err.message, 1, 2000);
          })
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    showAgreementContentModal(modalName,row){
      var self = this;
      self.agreenment.parkName = row.parkName;
      self.agreenment.title = row.agreementTitle;
      self.agreenment.content = row.agreementContent;
      self.toOpenModal(modalName);
    },
    openSelectParkModal(modalName) {
        var _self = this;
        _self.toOpenModal(modalName, 2);
        this.initParkTree("ParkTree");
    },
    initParkTree(treeId) {
        var _self = this;
        api.fetchGet('/parkingBaseData/getParkingBaseDataTree.do', {})
            .then(res => {
                //start..
                console.log('treetreetreetreetree', res)
                var data = res;
                if (data != null) {
                    var nodes = data.data;
                    var jsonStr = JSON.stringify(nodes);

                    jsonStr = jsonStr.replace(/(\"isArea\"\:true\,)/g, '"isArea": true,"chkDisabled":true, "nocheck":true,');
                    nodes = JSON.parse(jsonStr);
                    var settings = {
                        check: {
                            enable: true,
                            chkStyle: "radio",
                            radioType: "all"
                        },
                        view: {
                            showIcon: false,
                            showLine: false,
                        },
                        callback: {
                            onClick: function (event, treeId, treeNode) {
                                var treeObj = $.fn.zTree.getZTreeObj('ParkTree');
                                treeObj.checkNode(treeNode, true, false);
                                if (treeNode.isArea) {
                                    return;
                                }
                            },
                        }
                    };
                    $.fn.zTree.destroy("ParkTree");

                    var treeObj = $.fn.zTree.init($("#ParkTree"), settings, nodes);
                    treeObj.expandAll(true);

                } else {
                    _self.showToast('暂时没有停车场可选', 2, 3000);
                }
            }, err => { })

    },
    selectParkSure(){
      var self = this,
          nodes = [];
      var treeObj = $.fn.zTree.getZTreeObj("ParkTree");
      nodes = treeObj.getCheckedNodes(true); // 获取tree被勾选的节点
      if(nodes && nodes.length>0){
        //
        console.log(nodes[0]);
        var p = nodes[0];
        self.certifiRuleModel.parkName = p.name;
        self.certifiRuleModel.parkId = p.value;
        self.closed('selectParkModal', 2);
      }else{
        this.showToast('请选择一个停车场', 0, 2000)
        return;
      }
    },
    filterMultiCheck (selectionArr) {//必须定义获取多列的方法
      let result = [];
        selectionArr.map((item)=>{
          result.push(item.id);
        });
      return result;
    },
    handleSearchChange(item) {
      switch(item.name) {
        case 'reportDimension': this.changeReportDimension(item); break;
      }
    },
    changeReportDimension (item) {
      let value = item.value,
          ThisSearchItem = this.searchList[0];
       var today = [new Date(moment().add(-7, 'days').format('YYYY-MM-DD 00:00:00')), new Date(moment().add(1, 'days').format('YYYY-MM-DD 00:00:00'))];
      var month = [new Date(moment().add(-1, 'months').format('YYYY-MM-DD 00:00:00')), new Date(moment().format('YYYY-MM-DD 00:00:00'))];
      var year = [new Date(moment().add(-1, 'years').format('YYYY-MM-DD 00:00:00')), new Date(moment().format('YYYY-MM-DD 00:00:00'))];
      switch (value) {
        case 'day': ThisSearchItem.type = 'datePicker'; ThisSearchItem.pickerType = ''; ThisSearchItem.format = 'yyyy-MM-dd';ThisSearchItem.value = today;break;
        case 'month': ThisSearchItem.type = 'datePicker'; ThisSearchItem.pickerType = 'daterange'; ThisSearchItem.format = 'yyyy-MM';ThisSearchItem.value = month;break;
        case 'year': ThisSearchItem.type = 'datePicker'; ThisSearchItem.pickerType = 'daterange'; ThisSearchItem.format = 'yyyy';ThisSearchItem.value = year;break;
        case 'custom': ThisSearchItem.type = 'datePicker'; ThisSearchItem.pickerType = 'daterange'; ThisSearchItem.format = 'yyyy-MM-dd';ThisSearchItem.value = today;break;
      }
    }
  }
}